/**
 * 通用函数
 */
const log4js = require('./log4')
const jwt = require('jsonwebtoken')
const CODE = {
    SUCCESS: 200,
    PARAM_ERROR: 10001, //参数错误
    USER_ACCOUNT_ERROER: 20001, //账号或密码错误
    USER_LOGIN_ERROR: 30001, // 业务请求失败
    BUSINESS_ERROR: 4001, //业务请求失败
    AUTH_ERROR: 50001, //认证失败或token过期 
}
const add0 = (m) => {
    return m < 10 ? '0' + m : m
  }
  
module.exports = {
    pager({ pageNum = 1, pageSize = 10 }) {
        pageNum *= 1;
        pageSize *= 1;
        const skipIndex = (pageNum - 1) * pageSize;
        return {
            page: {
                pageNum,
                pageSize
            },
            skipIndex
        }
    },
    success(data = '', msg = '', code = CODE.SUCCESS) {
        log4js.debug(data)
        return {
            code, data, msg
        }
    },
    fail(msg = '', code = CODE.BUSINESS_ERROR, data = '') {
        log4js.debug(msg)
        return {
            code, data, msg
        }
    },
    CODE,
    decoded(authorization) {
        if (authorization) {
            let token = authorization.split(' ')[1]
            return jwt.verify(token, 'hyhadmin')
        }
        return ''
    },
  
    formateDate(date,flg){
        let time = new Date(parseFloat(date) * 1000)
        let y = time.getFullYear()
        let m = time.getMonth() + 1
        let d = time.getDate()
        let h = time.getHours()
        let mm = time.getMinutes()
        let s = time.getSeconds()
      
        if (flg === 'Y-M-D') {
          return y + '-' + add0(m) + '-' + add0(d)
        } else {
          return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s)
        }
    },
     getTreeMenu(rootList,id,list){
        for(let i=0;i<rootList.length;i++){
          let item = rootList[i]
          if(String(item.parentId.slice().pop()) == String(id)){
             list.push(item._doc)
          }
        }
        list.map(item=>{
          item['children'] = []
          this.getTreeMenu(rootList,item._id,item.children)
          if(item.children.length == 0){
            delete item.children
          }else if(item.children.length>0 && item.children[0].menuType ==2) {
            //快速区分按钮和菜单
            item.action =item.children
          }
        })
        return list
     }
}
